import axios from 'axios'
import store from '@/store'

import { Message } from 'element-ui'
import { REQUEST_SUCCESS, UNAUTHORIZED, NOT_FOUND, METHOD_NOT_ALLOWED } from '@/constant/common'
import qs from 'qs'

class Request {
  constructor() {
    this.service = axios.create({
      baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
      // baseURL: '',
      withCredentials: true, // send cookies when cross-domain requests
      timeout: 10000 // request timeout
    })
    // 请求拦截器
    this.service.interceptors.request.use(
      config => {
        if (store.getters.token) {
          config.headers['X-Token'] = store.getters.token
        }
        // TODO：待确认
        // 数组对象默认使用qs转换
        config.paramsSerializer = function (params) {
          return qs.stringify(params, { arrayFormat: 'repeat' })
        }

        return config
      },
      error => {
        // console.log('request error:' + JSON.stringify(error))
        return Promise.reject(error)
      }
    )
    // 响应拦截器
    this.service.interceptors.response.use(
      res => {
        return new Promise((resolve) => {
          // 若为成功请求，直接返回业务数据
          if (res.status === REQUEST_SUCCESS) {
            resolve(res)
          }
        })
      },
      error => {
        if (error.response) {
          if (error.response.status === UNAUTHORIZED) {
            Message.warning('未登录或会话超时，请重新登录')
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            }).then(resolve => {
              resolve()
            })
          } else if (error.response.status === NOT_FOUND) {
            Message.error('未找到服务，请确认')
          } else if (error.response.status === METHOD_NOT_ALLOWED) {
            Message.error('请求的方法不支持，请确认')
          } else {
            Message.error(error.response.data.message)
          }
          return Promise.reject(error)
        } else {
          Message.error('请求远程服务器失败')
        }
      }
    )
  }
  get(url, params) {
    const that = this
    return new Promise((resolve, reject) => {
      that.service.get(url,
        {
          params,
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        })
        .then(res => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
    })
  }
  // 新增
  post(url, params, showInfo, options) {
    const that = this
    return new Promise((resolve, reject) => {
      that.service.post(url, params, options)
        .then(res => {
          // 未定义时，默认显示提示；明确设置为false时，不显示提示
          if (showInfo === undefined || showInfo === true) {
            Message.info(res.data.message)
          }
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
    })
  }
  // 修改
  put(url, params, showInfo) {
    const that = this
    return new Promise((resolve, reject) => {
      that.service.put(url, params)
        .then(res => {
          // 未定义时，默认显示提示；明确设置为false时，不显示提示
          if (showInfo === undefined || showInfo === true) {
            Message.info(res.data.message)
          }
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
    })
  }
  // 移除
  remove(url, params, showInfo) {
    const that = this
    return new Promise((resolve, reject) => {
      that.service.delete(url, params)
        .then(res => {
          // 未定义时，默认显示提示；明确设置为false时，不显示提示
          if (showInfo === undefined || showInfo === true) {
            Message.info(res.data.message)
          }
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
    })
  }

  // 下载文件流
  download(url) {
    const link = document.createElement('a')
    link.href = process.env.VUE_APP_BASE_API + url
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

const httpRequest = new Request()
export default httpRequest
